import json
import os,time
from enum import Enum
from dotenv import load_dotenv
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..database.db import get_db
from pydantic import BaseModel
from ..crud.user_crud import get_user_by_name
from ..utils.jwt_handler import get_username
from ..models.ai_models.examTest import QuestionGenerator
from ..redisbase.redis_operations import check_key_exists,set_key,get_key,get_hash_data,get_hash_field,set_hash_data
from ..redisbase.redis_test import user_info_init
issues_router=APIRouter(prefix="/issue", tags=["出题"])

load_dotenv()
API_TOKEN=os.getenv("API_TOKEN")
@issues_router.get("/")
async def get_video():
    return {"message": "Hello World"}
class QuestionType(str, Enum):
    single_choice = "选择题"
    multiple_choice = "填空题"
    fill_in_the_blank = "简答题"
    judgment = "混合"

class IssuesParam(BaseModel):
    knowledge_point: str=...
    num_questions: int=...
    question_type: QuestionType=...
@issues_router.post("/")
async def create_issues(param: IssuesParam, db: Session = Depends(get_db),
                      username: str = Depends(get_username)):
    """
    # 参数说明
    - knowledge_point : 知识点
    - num_questions : 生成题的数量
    - question_type ： 题的类型（选择题、填空题、简答题、混合）
    """
    # if not check_key_exists(username):
    #     set_key(username,API_TOKEN)
    user=get_user_by_name(db,username)

    user = get_user_by_name(db, username).as_dict()
    user_id = user["id"]
    username = user["username"]
    current_date = time.strftime("%Y-%m-%d", time.localtime())
    user_info_init(user_id, username, current_date)
    new_video_quantity = int(get_hash_field(user_id, "questions_quantity")) + 1
    user_info = get_hash_data(user_id)
    user_info["questions_quantity"] = str(new_video_quantity)
    set_hash_data(user_id, user_info)

    question_generator = QuestionGenerator()
    result = question_generator.run(
        knowledge_point=param.knowledge_point,
        num_questions=param.num_questions,
        question_type=param.question_type.value,
    )
    return {
        "code":200,
        "message":"success",
        "data":{
            "issues":result,

        }
    }